package zozopo.attendance;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import zozopo.attendance.operations.OperatorAttendanceOS;
import zozopo.attendance.operations.OperatorAttendanceTB;
import zozopo.background.operator.operations.OperatorOS;
import zozopo.background.operator.operations.OperatorTB;
import zozopo.background.operator.operations.OperatorlimitedTB;
import zozopo.warehouse.operations.GoodsTB;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class CecalculatorAction extends ActionSupport implements Action,SessionAware,ServletResponseAware{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	//传入参数
	
	private File uploadfile;
	

	
 
	//传出参数

	OperatorTB operator;
	
	private HttpServletResponse response;
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}
	
	private Map<Object, Object> session;
	public void setSession(Map arg0) {
		// TODO Auto-generated method stub
		session = arg0;
	}
	public String execute(){
		
		LinkedHashMap<String,Calendar[]> lhm = new LinkedHashMap<String,Calendar[]>();
		try {
			
			BufferedReader  dr = new BufferedReader(new FileReader(uploadfile));
			
			String line = dr.readLine();
			while(line!= null){ 
				
				line= line.trim();
				if(line.contains("        ")){
					line = line.replace("        "," " );
				} 
				
				if(line.contains("  ")){
					line = line.replace("  "," " );
				} 
				
				String[] lineStrs =  line.split(" ");
				
				String id = "";
				String date = "";
				String timeStr = "";
				
				try{
					id = lineStrs[0];
					date = lineStrs[1];
					timeStr = lineStrs[2];
				
				
					if(!lhm.containsKey(date)){
						String[] dateSplist = date.split("/");
						String[] timeSplist = timeStr.split(":");
						
						Calendar calendar = new GregorianCalendar(
								Integer.valueOf(dateSplist[0]), Integer.valueOf(dateSplist[1]), Integer.valueOf(dateSplist[2])
								,Integer.valueOf(timeSplist[0]),Integer.valueOf(timeSplist[1]),0);
						
						Calendar[] calArr = {calendar,calendar};
						lhm.put(date, calArr);
						
					}else{
						Calendar[] calArr = lhm.get(date);
						
						String[] dateSplist = date.split("/");
						
						int y = Integer.valueOf(dateSplist[0]);
						int m = Integer.valueOf(dateSplist[1]);
						int d = Integer.valueOf(dateSplist[2]);
						
						String[] timeSplist = timeStr.split(":");
						
						Calendar calendar = new GregorianCalendar(
								y, m, d
								,Integer.valueOf(timeSplist[0]),Integer.valueOf(timeSplist[1]),0);
						
						if(calendar.getTimeInMillis() < calArr[0].getTimeInMillis()){
							calArr[0] = calendar;
						}
						
						if(calendar.getTimeInMillis() > calArr[1].getTimeInMillis()){
							calArr[1] = calendar;
						}
						lhm.put(date, calArr);
						
					}
					System.out.println(line);
				}catch(Exception e){
					line = dr.readLine();
					continue;
				}
				line = dr.readLine();
		} 
			
			
			//re.r
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //写入到FileInputStream
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			write2Excel(uploadfile.getName(),response,lhm);
		} catch (RowsExceededException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return NONE;
		
	}

	public void validate() {
		/*/权限处理

		OperatorTB operator = (OperatorTB)session.get("operatorInfo"); 
		if(operator == null){//是否登陆
			addFieldError("errormessage",getText("operator.timeoutornotlogin"));
			return ; 
		} */
	}
	
	
	public static void write2Excel(String fileName,
			HttpServletResponse response,LinkedHashMap<String,Calendar[]> lhm) throws SQLException, IOException,
			RowsExceededException, WriteException {
			// 获得导出数据的列数
			String[] title = { "日期", "上班打卡时间", "下班打卡时间",  "迟到时间(分钟)" ,"自由加班(分钟)","是否迟到"};
			
			response.setContentType("application/x-msdownload");
			// 定义打印出来后的报表名
			String dispposition = "=?UTF-8?Q?attachment; filename=" + fileName
			+ ".xls";
			response.setHeader("Content-Disposition", dispposition);
			OutputStream os = response.getOutputStream();
			WritableWorkbook wwb = Workbook.createWorkbook(os);
			WritableSheet ws = wwb.createSheet(fileName, 0);
			
			try{
					
				for(int i=0; i<title.length;i++){
					Label label1 = new Label(i, 0, title[i]);
					ws.addCell(label1);
				}
				
				
				
				int i=0;
				
				
				 Set<String> key = lhm.keySet();
				 
					//1小时=60分钟=3600秒=3600000
				long mins = 60L * 1000L;
					 //long day= 24L * 60L * 60L * 1000L;计算天数之差

						
					 
					 
					 
				for (Iterator it = key.iterator(); it.hasNext();) {
					i++;
				          String s = (String) it.next();
				            
				           String[] dateSplist = s.split("/");
				            
				            Calendar beginOfficetime = new GregorianCalendar(
				            		Integer.valueOf(dateSplist[0]), Integer.valueOf(dateSplist[1]), Integer.valueOf(dateSplist[2])
									,10,0,0);
							
							Calendar endOfficetime = new GregorianCalendar(
									Integer.valueOf(dateSplist[0]), Integer.valueOf(dateSplist[1]), Integer.valueOf(dateSplist[2])
									,18,30,0);
				            
				            Calendar[] calArr = lhm.get(s);
				            DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				            String begin = df.format(calArr[0].getTime());
				            String end = df.format(calArr[1].getTime());
				            
				            long lateMins = (beginOfficetime.getTime().getTime() - calArr[0].getTime().getTime())/mins;
				            long otMins = -(endOfficetime.getTime().getTime() - calArr[1].getTime().getTime())/mins;
				            
				            System.out.println(s + " " + begin +" "+ end+" "+ lateMins+" "+ otMins);
				            
				            Label label1 = new Label(0, i, s+"");
							Label label2 = new Label(1, i, begin+" ");
							Label label3 = new Label(2, i, end+" ");
							Label label4 = new Label(3, i, lateMins+" ");
							Label label5 = new Label(4, i, otMins+" ");
					
							ws.addCell(label1);
							ws.addCell(label2);
							ws.addCell(label3);
							ws.addCell(label4);
							ws.addCell(label5);

				 }
			} catch (Exception ex) {
			ex.printStackTrace();
			} finally {
			// 关闭Excel工作薄对象
			wwb.write();
			wwb.close();
			os.close();
			}
			}
	public File getUploadfile() {
		return uploadfile;
	}
	public void setUploadfile(File uploadfile) {
		this.uploadfile = uploadfile;
	}
		
	
	
	
	

}
